import { ProTable } from '@ant-design/pro-components';
import {
  Button,
  Popconfirm,
  message,
  Tag,
  Upload,
  Image,
  Table,
  Space,
  Breadcrumb,
} from 'antd';
import { PageContainer } from '@ant-design/pro-layout';
import { useRequest } from 'umi';
import type { UploadProps } from 'antd';
import { UploadOutlined, FileSearchOutlined } from '@ant-design/icons';
import React, { useRef } from 'react';
import type { ProFormInstance } from '@ant-design/pro-components';
import moment from 'moment';
import ImportExcel from '@/pages/LabManage/component/ImportExcel';
import { useBoolean } from 'ahooks';

import {
  ModalForm,
  ProForm,
  ProFormSelect,
  ProFormText,
  ProFormDatePicker,
} from '@ant-design/pro-components';

export default () => {
  const formRef = useRef<ProFormInstance>();
  const editformRef = useRef<ProFormInstance>();
  const [selectRow, { toggle }] = useBoolean(false);

  const updateStatus = useRequest(
    (data = {}) => {
      return {
        url: 'http://10.1.40.84:9993/common/updateStatus',
        method: 'POST',
        headers: {
          Authorization: localStorage.getItem('token') || '',
        },
        data,
      };
    },
    {
      manual: true,
    },
  );

  const props: UploadProps = {
    name: 'file',
    action: 'http://10.1.40.84:9993/common/uploadFile',
    headers: {
      Authorization: localStorage.getItem('token') || '',
    },
    maxCount: 1,
    accept: '.png,.jpeg,.jpg',
    onChange(info) {
      if (info.file.status !== 'uploading') {
        console.log(info.file, info.fileList);
      }
      if (info.file.status === 'done') {
        formRef.current?.setFieldsValue({ picPath: info.file.response.data });
        editformRef.current?.setFieldsValue({
          picPath: info.file.response.data,
        });
        message.success(`${info.file.name} 上传成功！`);
      } else if (info.file.status === 'error') {
        message.error(`${info.file.name} 上传失败！`);
      }
    },
  };
  const props1: UploadProps = {
    name: 'file',
    action: 'http://10.1.40.84:9993/common/uploadFile',
    headers: {
      Authorization: localStorage.getItem('token') || '',
    },
    maxCount: 1,
    onChange(info) {
      if (info.file.status !== 'uploading') {
        console.log(info.file, info.fileList);
      }
      if (info.file.status === 'done') {
        formRef.current?.setFieldsValue({ annexPath: info.file.response.data });
        editformRef.current?.setFieldsValue({
          annexPath: info.file.response.data,
        });
        message.success(`${info.file.name} 上传成功！`);
      } else if (info.file.status === 'error') {
        message.error(`${info.file.name} file upload failed.`);
      }
    },
  };
  //获取 开放共享 列表
  const findAllShare = useRequest((data = undefined) => {
    return {
      url: `http://10.1.40.84:9993/openShare/findAllShare`,
      method: 'POST',
      headers: {
        Authorization: localStorage.getItem('token') || '',
      },
      data,
    };
  });
  //新增 开放共享
  const insertShare = useRequest(
    (data = undefined) => {
      return {
        url: `http://10.1.40.84:9993/openShare/insertShare`,
        method: 'POST',
        headers: {
          Authorization: localStorage.getItem('token') || '',
        },
        data,
      };
    },
    {
      manual: true,
    },
  );
  //删除 开放共享
  const delShare = useRequest(
    (data = undefined) => {
      return {
        url: `http://10.1.40.84:9993/openShare/delShare`,
        method: 'POST',
        headers: {
          Authorization: localStorage.getItem('token') || '',
        },
        data,
      };
    },
    {
      manual: true,
    },
  );
  //编辑 开放共享
  const updateShare = useRequest(
    (data = undefined) => {
      return {
        url: `http://10.1.40.84:9993/openShare/updateShare`,
        method: 'POST',
        headers: {
          Authorization: localStorage.getItem('token') || '',
        },
        data,
      };
    },
    {
      manual: true,
    },
  );
  const confirm = (e: any) => {
    delShare.run({ id: e.id }).then(() => {
      findAllShare.run();
      message.success('删除成功');
    });
  };
  const cancel = (e: any) => {
    message.error('已取消');
  };
  const columns = [
    {
      title: '序号',
      align: "center",
      dataIndex: 'seq',
      key: 'seq',
      width: 60,
      // copyable: true,
      hideInSearch: true,
    },
    {
      title: '开放年份',
      align: "center",
      dataIndex: 'year',
      key: 'year',
      valueType: 'dateYear',
      hideInTable: true,
    },
    {
      title: '年份',
      align: "center",
      dataIndex: 'year',
      key: 'year',
      sorter: {
        compare: (a, b) => a.year - b.year,
      },
      hideInSearch: true,
    },
    {
      title: '时间',
      align: "center",
      dataIndex: 'eventTime',
      key: 'eventTime',
      hideInSearch: true,
      // render: (text: any) => <span>{moment(text).format('YYYY-MM-DD')}</span>
    },
    {
      title: '开放形式',
      align: "center",
      dataIndex: 'eventType',
      key: 'eventType',
      hideInSearch: true,
    },

    {
      title: '开放对象',
      align: "center",
      dataIndex: 'eventFor',
      key: 'eventFor',
      hideInSearch: true,
    },

    {
      title: '传播形式',
      align: "center",
      dataIndex: 'spreadType',
      key: 'spreadType',
      hideInSearch: true,
    },

    {
      title: '报道链接',
      align: "center",
      dataIndex: 'reportLink',
      key: 'reportLink',
      hideInSearch: true,
      render: (text: any, record: any) => {
        if (record.reportLink !== null) {
          return (
            <a
              onClick={() => {
                window.open(text);
              }}
            >
              查看链接
            </a>
          );
        } else {
          return <span>暂无链接</span>;
        }
      },
    },
    {
      title: '材料',
      align: "center",
      dataIndex: 'annexPath',
      key: 'annexPath',
      hideInSearch: true,
      render: (text: any, record: any) => {
        if (record.annexPath !== null) {
          return (
            <a
              onClick={() => {
                window.open(text);
              }}
            >
              下载
            </a>
          );
        } else {
          return <span>暂无材料</span>;
        }
      },
    },
    {
      title: '图片',
      align: "center",
      dataIndex: 'picPath',
      key: 'picPath',
      hideInSearch: true,
      width: '140px',
      render: (text: any) => {
        if (text !== null) {
          return <Image src={text} width={130}></Image>;
        } else {
          return null;
        }
      },
    },
    {
      title: '操作',
      align: "center",
      key: 'option',
      // width: 120,
      valueType: 'option',
      render: (text: any, record: any) => [
        <ModalForm
          grid={true}
          title="编辑学术交流"
          trigger={<a key="1">编辑</a>}
          autoFocusFirstInput
          modalProps={{
            onCancel: () => console.log('run'),
          }}
          submitTimeout={2000}
          onFinish={async (values) => {
            console.log(values);
            updateShare.run(values).then(() => {
              message.info('编辑成功！');
              findAllShare.run();
            });
            return true;
          }}
          initialValues={{ ...record, year: record.year + '' }}
          key="1"
          formRef={editformRef}
          onVisibleChange={() => {
            editformRef.current?.resetFields();
          }}
        >
          <ProFormText name="id" hidden />
          <ProForm.Group>
            <ProFormDatePicker.Year
              colProps={{ span: 6 }}
              name="year"
              label="年份"
            />
            <ProFormDatePicker
              colProps={{ span: 6 }}
              name="eventTime"
              label="时间"
              rules={[{ required: true, message: '请选择' }]}
            />
            <ProFormSelect
              colProps={{ span: 6 }}
              options={[
                {
                  value: '参观访问',
                  label: '参观访问',
                },
                {
                  value: '科技夏令营',
                  label: '科技夏令营',
                },
                {
                  value: '科普讲座',
                  label: '科普讲座',
                },
                {
                  value: '学生实践',
                  label: '学生实践',
                },
                {
                  value: '其他活动',
                  label: '其他活动',
                },
              ]}
              name="eventType"
              label="开放形式"
              rules={[{ required: true, message: '请选择' }]}
            />
            <ProFormSelect
              colProps={{ span: 6 }}
              options={[
                {
                  value: '大学生',
                  label: '大学生',
                },
                {
                  value: '中学生',
                  label: '中学生',
                },
                {
                  value: '小学生',
                  label: '小学生',
                },
                {
                  value: '其他公众',
                  label: '其他公众',
                },
              ]}
              name="eventFor"
              label="开放对象"
              rules={[{ required: true, message: '请选择' }]}
            />
          </ProForm.Group>
          <ProForm.Group>
            <ProFormSelect
              name="spreadType"
              label="传播形式"
              options={[
                {
                  value: '人民日报',
                  label: '人民日报',
                },
                {
                  value: '新华社',
                  label: '新华社',
                },
                {
                  value: '中央电视台',
                  label: '中央电视台',
                },
                {
                  value: '科技日报',
                  label: '科技日报',
                },
                {
                  value: '其他重要新闻媒体',
                  label: '其他重要新闻媒体',
                },
                {
                  value: '新媒体',
                  label: '新媒体',
                },
              ]}
              rules={[{ required: true, message: '请选择' }]}
            />
            <ProFormText name="reportLink" label="报道链接" />

            <ProFormText name="picPath" hidden />
            <ProFormText name="annexPath" hidden />

            <Upload {...props}>
              <Button
                icon={<UploadOutlined />}
                type="link"
                style={{ marginTop: 30 }}
              >
                上传照片（单张）
              </Button>
            </Upload>
            <Upload {...props1}>
              <Button
                icon={<UploadOutlined />}
                type="link"
                style={{ marginTop: 30 }}
              >
                上传材料（上传会议照片，以会议名称命名）
              </Button>
            </Upload>
          </ProForm.Group>
        </ModalForm>,
        <Popconfirm
          key={'2'}
          title="确定删除吗？"
          onConfirm={() => confirm(record)}
          onCancel={() => cancel}
          okText="确定"
          cancelText="取消"
        >
          <a href="#">删除</a>
        </Popconfirm>,
      ],
    },
  ];

  const Refresh = () => {
    findAllShare.run();
  };
  return (
    <PageContainer
      header={{
        title: null,
        breadcrumb: (
          <Breadcrumb>
            <Breadcrumb.Item>合作交流</Breadcrumb.Item>
            <Breadcrumb.Item>开放共享</Breadcrumb.Item>
          </Breadcrumb>
        ),
        extra: [
        ],
      }}
    >
      <ProTable
        columns={columns}
        dataSource={findAllShare?.data}
        rowKey="id"
        pagination={{
          showQuickJumper: true,
        }}
        onSubmit={(e: any) => {
          findAllShare.run(e);
        }}
        onReset={() => {
          findAllShare.run();
        }}
        loading={findAllShare.loading}
        dateFormatter="string"
        headerTitle="开放共享列表"
        options={false}
        toolBarRender={() => [
          <ImportExcel tableName={'OPEN_SHARE'} Refresh={Refresh} />,
          <Button
            type="primary"
            onClick={() => {
              window.open(
                'http://10.1.40.84:9993/file/model/OPEN_SHARE_模板.xlsx ',
              );
            }}
          >
            下载模版
          </Button>,

          <ModalForm
            grid={true}
            title="新增开放共享"
            trigger={
              <Button key="primary" type="primary">
                新增开放共享
              </Button>
            }
            autoFocusFirstInput
            modalProps={{
              onCancel: () => console.log('run'),
            }}
            submitTimeout={2000}
            onFinish={async (values) => {
              insertShare.run(values).then(() => {
                findAllShare.run();
                message.info('添加成功！');
              });
              return true;
            }}
            key="1"
            formRef={formRef}
            onVisibleChange={() => {
              formRef.current?.resetFields();
            }}
          >
            <ProForm.Group>
              <ProFormDatePicker.Year
                colProps={{ span: 6 }}
                name="year"
                label="年份"
              />
              <ProFormDatePicker
                colProps={{ span: 6 }}
                name="eventTime"
                label="时间"
                rules={[{ required: true, message: '请选择' }]}
              />
              <ProFormSelect
                colProps={{ span: 6 }}
                options={[
                  {
                    value: '参观访问',
                    label: '参观访问',
                  },
                  {
                    value: '科技夏令营',
                    label: '科技夏令营',
                  },
                  {
                    value: '科普讲座',
                    label: '科普讲座',
                  },
                  {
                    value: '学生实践',
                    label: '学生实践',
                  },
                  {
                    value: '其他活动',
                    label: '其他活动',
                  },
                ]}
                name="eventType"
                label="开放形式"
                rules={[{ required: true, message: '请选择' }]}
              />
              <ProFormSelect
                colProps={{ span: 6 }}
                options={[
                  {
                    value: '大学生',
                    label: '大学生',
                  },
                  {
                    value: '中学生',
                    label: '中学生',
                  },
                  {
                    value: '小学生',
                    label: '小学生',
                  },
                  {
                    value: '其他公众',
                    label: '其他公众',
                  },
                ]}
                name="eventFor"
                label="开放对象"
                rules={[{ required: true, message: '请选择' }]}
              />
            </ProForm.Group>
            <ProForm.Group>
              <ProFormSelect
                options={[
                  {
                    value: '人民日报',
                    label: '人民日报',
                  },
                  {
                    value: '新华社',
                    label: '新华社',
                  },
                  {
                    value: '中央电视台',
                    label: '中央电视台',
                  },
                  {
                    value: '科技日报',
                    label: '科技日报',
                  },
                  {
                    value: '其他重要新闻媒体',
                    label: '其他重要新闻媒体',
                  },
                  {
                    value: '新媒体',
                    label: '新媒体',
                  },
                ]}
                name="spreadType"
                label="传播形式"
                rules={[{ required: true, message: '请选择' }]}
              />
              <ProFormText name="reportLink" label="报道链接" />

              <ProFormText name="picPath" hidden />
              <ProFormText name="annexPath" hidden />

              <Upload {...props}>
                <Button
                  icon={<UploadOutlined />}
                  type="link"
                  style={{ marginTop: 30 }}
                >
                  上传照片（单张）
                </Button>
              </Upload>
              <Upload {...props1}>
                <Button
                  icon={<UploadOutlined />}
                  type="link"
                  style={{ marginTop: 30 }}
                >
                  上传材料（上传会议照片，以会议名称命名）
                </Button>
              </Upload>
            </ProForm.Group>
          </ModalForm>,
        ]}
        search={{ labelWidth: 'auto' }}
        rowSelection={
          selectRow
            ? {
                selections: [Table.SELECTION_ALL, Table.SELECTION_INVERT],
              }
            : false
        }
        tableAlertOptionRender={({
          selectedRowKeys,
          selectedRows,
          onCleanSelected,
        }) => (
          <Space size={16}>
            <a style={{ marginLeft: 8 }} onClick={onCleanSelected}>
              取消选择
            </a>
            <a
              onClick={() => {
                updateStatus
                  .run({
                    tableName: 'OPEN_SHARE',
                    ids: selectedRowKeys,
                    status: 2, //审核通过
                  })
                  .then(() => {
                    message.success('操作成功');
                    onCleanSelected();
                    toggle();
                    findAllShare.run();
                  });
              }}
            >
              审核通过
            </a>
            <a
              onClick={() => {
                updateStatus
                  .run({
                    tableName: 'OPEN_SHARE',
                    ids: selectedRowKeys,
                    status: 3, //拒绝
                  })
                  .then(() => {
                    message.success('操作成功');
                    onCleanSelected();
                    toggle();
                    findAllShare.run();
                  });
              }}
            >
              拒绝
            </a>
          </Space>
        )}
      />
    </PageContainer>
  );
};
